package com.bmd.backgroundmanger.controller;

import com.bmd.backgroundmanger.commons.Result;
import com.bmd.backgroundmanger.entity.UserAnswer;
import com.bmd.backgroundmanger.mapper.UserAnswerMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 测试控制器 - 用于调试数据库问题
 */
@RestController
@RequestMapping("/test")
@Tag(name = "测试接口")
public class TestController {

    @Resource
    private UserAnswerMapper userAnswerMapper;

    @GetMapping("/ping")
    @Operation(summary = "测试接口连通性")
    public Result<String> ping() {
        return Result.success("服务正常运行");
    }

    @PostMapping("/saveAnswer")
    @Operation(summary = "直接测试保存答案")
    public Result<String> saveAnswer() {
        try {
            UserAnswer userAnswer = new UserAnswer();
            userAnswer.setUserId(1);
            userAnswer.setQuestionId(1);
            userAnswer.setAnswerContent("A");
            userAnswer.setIsCorrect(true);
            userAnswer.setScore(5);
            userAnswer.setSubmitTime(LocalDateTime.now());
            userAnswer.setCreateTime(LocalDateTime.now());

            System.out.println("准备插入答题记录: " + userAnswer);
            
            int result = userAnswerMapper.insert(userAnswer);
            System.out.println("插入结果: " + result);
            System.out.println("生成的ID: " + userAnswer.getAnswerId());

            if (result > 0) {
                return Result.success("测试保存成功，生成ID: " + userAnswer.getAnswerId());
            } else {
                return Result.error(500, "测试保存失败");
            }
        } catch (Exception e) {
            System.err.println("测试保存异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error(500, "测试保存异常: " + e.getMessage());
        }
    }

    @GetMapping("/listAnswers")
    @Operation(summary = "查看所有答题记录")
    public Result<List<UserAnswer>> listAnswers() {
        try {
            List<UserAnswer> answers = userAnswerMapper.selectList(null);
            System.out.println("查询到答题记录数量: " + answers.size());
            return Result.success(answers);
        } catch (Exception e) {
            System.err.println("查询异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error(500, "查询异常: " + e.getMessage());
        }
    }

    @DeleteMapping("/clearAnswers")
    @Operation(summary = "清空测试数据")
    public Result<String> clearAnswers() {
        try {
            int result = userAnswerMapper.delete(null);
            return Result.success("清空完成，删除了 " + result + " 条记录");
        } catch (Exception e) {
            return Result.error(500, "清空失败: " + e.getMessage());
        }
    }
} 